package com.heima.wemedia.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.common.ThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1.判断文件参数是否合规（文件不能为空，必须是图片类型）
        //1.1 文件不能为空
        if(multipartFile.isEmpty() || multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件不能为空");
        }

        try {
            //1.2 必须是图片类型
            String type = FileTypeUtil.getType(multipartFile.getInputStream());
            if(!WemediaConstants.IMAGE_TYPE_LIST.contains(type)){ //当获取的文件类型不是在图片类型范围类时，说明是伪造的图片或者上传的不是图片
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件必须是图片");
            }

            //2.生成唯一文件名
            String fileNamePrefix = IdUtil.fastSimpleUUID(); //文件名前缀：uuid的值
            String fileNamePostfix = "." + type; //文件名后缀：.类型
            String fileNameFull = fileNamePrefix + fileNamePostfix;//拼接完整文件名

            //3.将文件上传到MinIO得到url
            String url = fileStorageService.uploadImgFile("", fileNameFull, multipartFile.getInputStream());

            //4.构建素材数据保存到素材表中
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(ThreadLocalUtil.getUserId()); //登录的自媒体用户id
            wmMaterial.setUrl(url);//素材在minio中的路径
            wmMaterial.setType(0);//文件类型：0-图片 1-视频
            wmMaterial.setIsCollection(0);//是否收藏：0-未收藏 1-已收藏
            wmMaterial.setCreatedTime(new Date());//上传时间
            this.save(wmMaterial);

            //5.响应素材数据（为了前端回显）
            return ResponseResult.okResult(wmMaterial);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "上传失败");
        }
    }


    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.设置分页参数默认值
        dto.checkParam();

        //2.拼接查询条件
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //2.1 拼接固定条件：根据userId查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId, ThreadLocalUtil.getUserId());
        //2.2 拼接动态条件：根据isCollection查询
//        if(dto.getIsCollection()>0){
//            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
//        }
        lambdaQueryWrapper.eq(dto.getIsCollection()>0, WmMaterial::getIsCollection, dto.getIsCollection());
        //2.3 设置结果要求：根据createdTime倒排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //3.执行分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        this.page(page, lambdaQueryWrapper);

        //4.封装分页响应结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }
}
